
package cn.afactory.tygz.ui.sns;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.harwkin.nb.camera.PageBigImageActivity;
import com.harwkin.nb.camera.callback.CameraImageListener;
import com.harwkin.nb.camera.model.PicsItem;
import com.harwkin.nb.camera.model.PicsItemList;
import com.harwkin.nb.camera.options.CameraOptions;
import com.harwkin.nb.camera.pop.CameraPop;
import com.harwkin.nb.camera.pop.CameraPopListener;
import com.harwkin.nb.camera.type.OpenType;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.utils.ImageLoaderUtil;
import com.tendcloud.tenddata.TCAgent;

import java.util.ArrayList;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.ImageUploadType;
import cn.afactory.tygz.model.SnsTopicInfo;
import cn.afactory.tygz.model.UploadFileInfoList;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.base.BaseActivity;
import cn.afactory.tygz.ui.base.fragments.NearByForumsFragment;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.sns.controller.SnsControler;


@ContentView(R.layout.ac_publish_subject)
public class PublishSubjectActivity extends BaseActivity {
    public static final int REQ_LOCATION_CODE = 1003;

    public static final int REQ_TOPIC_ID = 1004;
    public static final int PUBLISH_REQUEST_CODE = 11;
    public static final int PUBLISH_RESULT_CODE = 12;
    @ViewInject(R.id.msg_text)
    private EditText mMsgTextView;
    @ViewInject(R.id.iv_image)
    private ImageView mThumbImageView;
    @ViewInject(R.id.iv_image_delete)
    private ImageView mDeleteView;
    @ViewInject(R.id.ll_select_subject)
    private LinearLayout mSelectTopicView;
    @ViewInject(R.id.tv_select_subject)
    private TextView mSelectTopicName;
    private SnsTopicInfo mTopicInfo = null;
    private String mImagePath = null;

    private long mTopicId;
    private String mTopicName;
    private SnsControler mController;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SnsControler.MSG_PUBLISH_SUBJECT_OK:
                LocalUtils.showToast(PublishSubjectActivity.this, getString(R.string.toast_publish_forum_ok));
//                setResult(PublishSubjectActivity.PUBLISH_RESULT_CODE);
                Intent intent = new Intent();
                intent.setAction(NearByForumsFragment.PUBLISH_BROADCAST_ACTION);
                sendBroadcast(intent);
                setResult(RESULT_OK);
                finish();
                break;
            case SnsControler.MSG_PUBLISH_SUBJECT_KO:
                hideLoadingView();
                LocalUtils.showToast(PublishSubjectActivity.this,getString(R.string.toast_publish_forum_ko));
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);

        mTopicId = getIntent().getLongExtra(SPUtils.EXTRA_POST_ID, -1);
        mTopicName = getIntent().getStringExtra(SPUtils.EXTRA_TITLE);
        if(mTopicId > 0){
            mTopicInfo = new SnsTopicInfo();
            mTopicInfo.topicName = mTopicName;
            mTopicInfo.topicId = mTopicId;
        }

        initUI();
        initTitleBar();
        initCameraPop();
        mController = new SnsControler(getApplicationContext(),mUIHandler,"NearByForums");
    }

    public void onResume() {
        super.onResume();
        TCAgent.onResume(this);
    }

    /**
     * 跳转到帖子发布页面
     */
    public static void gotoPublishSubject(Context context,String title,long topicId){
        Intent intent = new Intent(context,PublishSubjectActivity.class);
        intent.putExtra(SPUtils.EXTRA_TITLE,title);
        intent.putExtra(SPUtils.EXTRA_POST_ID,topicId);
        context.startActivity(intent);
    }

    /**
     * 跳转到帖子发布页面
     */
    public static void gotoPublishSubject(Activity context,String title,long topicId,int reqCode){
        Intent intent = new Intent(context,PublishSubjectActivity.class);
        intent.putExtra(SPUtils.EXTRA_TITLE,title);
        intent.putExtra(SPUtils.EXTRA_POST_ID,topicId);
        context.startActivityForResult(intent,reqCode);
    }
    /**
     * 跳转到帖子发布页面
     */
    public static void gotoPublishSubject(Fragment context, String title, long topicId, int reqCode){
        Intent intent = new Intent(context.getActivity(),PublishSubjectActivity.class);
        intent.putExtra(SPUtils.EXTRA_TITLE,title);
        intent.putExtra(SPUtils.EXTRA_POST_ID,topicId);
        context.startActivityForResult(intent,reqCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == PageBigImageActivity.REQ_CHOOSE_MAP){
            if(resultCode == Activity.RESULT_OK) {
                PicsItemList t = (PicsItemList)data.getSerializableExtra(PageBigImageActivity.IMAGE_LIST_DATA);
                if (t.list.size() == 0) {
                    doDeleteImage();
                }
            }
        } else if(requestCode == REQ_TOPIC_ID){
            if(resultCode == Activity.RESULT_OK){
                if(data != null && data.getSerializableExtra(SPUtils.EXTRA_DATA) != null) {
                    SnsTopicInfo snsTopicInfo = (SnsTopicInfo) data.getSerializableExtra(SPUtils.EXTRA_DATA);
                    mTopicInfo = snsTopicInfo;
                    if(mTopicInfo != null){
                        mSelectTopicName.setText(mTopicInfo.topicName);
                    }
                }
            }
        } else {
            if (mCameraPop != null) {
                mCameraPop.forResult(requestCode, resultCode, data);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initTitleBar(){
        setTitleText("说一说");
        setRightButton(getString(R.string.label_btn_publish_forum), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mImagePath != null) {
                    doUploadImage();
                } else {
                    doPublishForum();
                }
            }
        });
    }

    private void initUI(){
        mThumbImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mImagePath == null){
                    doAddNewImage();
                }else{
                    doViewBigImage();
                }
            }
        });

        mDeleteView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDelPicDialog();
            }
        });

        mSelectTopicView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSelectTopic();
            }
        });

        if(mTopicInfo != null){
            mSelectTopicName.setText(mTopicInfo.topicName);
        }
    }

    //添加新图片
    private void doAddNewImage(){
        if(mCameraPop != null) {
            mCameraPop.showMenu(mThumbImageView);
        }
    }
    //查看大图
    private void doViewBigImage(){
        ArrayList<PicsItem> mPicItems = new ArrayList<PicsItem>();
        PicsItem picsItem = new PicsItem();
        mPicItems.add(picsItem);
        picsItem.image = mImagePath;
        startActivityForResult(PageBigImageActivity.getIntent(mContext, mPicItems, 0, true, true),
                PageBigImageActivity.REQ_CHOOSE_MAP);
    }
    //删除图片
    private void doDeleteImage(){
        mThumbImageView.setImageResource(R.drawable.hc_button_add);
        mImagePath = null;
        mDeleteView.setVisibility(View.GONE);
    }

    Dialog mDelDialog;
    private void showDelPicDialog(){
        mDelDialog = DialogUtil.showMessageDialog(this,
                null,
                getString(R.string.dlg_msg_delete_pic),
                getString(R.string.label_btn_delete),
                getString(R.string.label_btn_cancel),
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doDeleteImage();
                        if(mDelDialog != null){
                            mDelDialog.dismiss();
                        }
                    }
                },
                null);
    }
    //选择话题
    private void doSelectTopic(){
        mTopicInfo = null;
        NaviUtils.gotoSelectTopicId(this);
    }
    //发布帖子
    private int mFileFiledId = -1;
    private void doPublishForum(){
        String msgContent = mMsgTextView.getText().toString();
        if(msgContent == null){
            LocalUtils.showToast(this,"亲，捎带说几句!");
            return;
        }
        showLoadingView("发布中...,请稍候！");
        mController.publishSubject(msgContent, mTopicInfo == null ? -1 : mTopicInfo.topicId, mFileFiledId);
    }

    private int source = 1;
    private CameraPop mCameraPop;
    //初始化图片的菜单项
    private void initCameraPop(){
        mCameraPop = new CameraPop(this, new CameraPopListener() {
            @Override
            public void onCamreaClick(CameraOptions options) {
                options.setOpenType(OpenType.OPEN_CAMERA);
                mCameraPop.process();
            }

            @Override
            public void onPickClick(CameraOptions options) {
                options.setOpenType(OpenType.OPEN_GALLERY);
                mCameraPop.process();
            }

            @Override
            public void onDelClick() {

            }
        }, new CameraImageListener() {
            @Override
            public void onSelectedAsy(String imgPath) {
                if(imgPath != null){
                    mImagePath = imgPath;
                    mDeleteView.setVisibility(View.VISIBLE);
                    ImageLoaderUtil.loadLocalImage(mThumbImageView, imgPath);
                }
            }
        });
    }

    /**
     * 上传图片
     */
    private void doUploadImage(){
        showLoadingView("");
        NetManager.getInstance(this).doUploadImage(mImagePath, ImageUploadType.FORUMS,
                new OnResponseListener<UploadFileInfoList>() {
            @Override
            public void onComplete(boolean isOK, UploadFileInfoList result, int errorCode, String errorMsg) {
                hideLoadingView();
                if(isOK && result != null && result.data != null && result.data.size() > 0){
                    mFileFiledId = result.data.get(0).fileId;
                    doPublishForum();
                }else{
                    LocalUtils.showToast(PublishSubjectActivity.this,"图片上传失败！");
                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                hideLoadingView();
                LocalUtils.showToast(PublishSubjectActivity.this, errorMessage);
            }

        });
    }
}
